package com.okaysoft.ofb.account

import org.springframework.dao.DataIntegrityViolationException
import com.okaysoft.ofb.account.User
import com.okaysoft.ofb.account.Role
import grails.converters.JSON

class UserController {
    def springSecurityService
    static allowedMethods = [save: "POST", update: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list() {
    }

    def listJson() {
        params.max = Math.min(params.rows ? params.int('rows') : 10, 100)
        params.page = params.page ? params.int('page') : 0
        params.offset = (params.page - 1) * params.max
        def users = User.list(params)
        users = users.collect {user->
            [id: user.id, name:user.name,username:user.username,accountExpired:user.accountExpired,
                    accountLocked:user.accountLocked,authorities:user.authorities.collect {"${it.id}"},
                    roles:user.authorities.collect {it.name},enabled:user.enabled,password:user.password,
                    passwordExpired:user.passwordExpired,password_new:'',departmentName:user?.department?.name,
                    departmentId:user?.department?.id]
        }
        render([total: User.count(), rows: users] as JSON)
    }

    def save() {
        if (params.password_new) {
            params.password = params.password_new
        }

        def roleIds = params.role

        def userInstance = User.get(params.id)
        if (!userInstance) {
            userInstance = new User()
        }

        userInstance.properties = params

        if (!userInstance.save(flush: true)) {
            def fialure = [status: 0, msg: message(code: 'default.save.failure.message', default: 'Save failure')] as JSON
            render(fialure.toString())
            return
        }

        UserRole.removeAll(userInstance)
        roleIds.each {rid->
            def role = Role.get(rid)
            UserRole.create userInstance, role, true
        }
        def succ = [status: 1, msg: message(code: 'default.save.success.message', default: 'Save success')] as JSON
        render(succ.toString())
    }

    def show() {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
            redirect(action: "list")
            return
        }

        [userInstance: userInstance]
    }

    def delete() {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            render([status: 0, msg:  message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])] as JSON)
            return
        }

        //当前用户不能删除自己
        if (userInstance.id == springSecurityService.principal.id) {
            render([status: 0, msg:  message(code: 'default.not.deleted.message', args: [message(code: 'user.label', default: 'User'), params.id])] as JSON)
            return
        }

        try {
            UserRole.removeAll(userInstance)
            userInstance.delete(flush: true)
            render([status: 1, msg:  message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), params.id])] as JSON)

        }
        catch (DataIntegrityViolationException e) {
            render([status: 0, msg:  message(code: 'default.not.deleted.message', args: [message(code: 'user.label', default: 'User'), params.id])] as JSON)
        }
    }

    def changePassword() {

    }

    def updatePassword() {
        def userInstance = User.get(springSecurityService.principal.id)

        def password = params.password
        def passwordnew = params.password_new
        def passwordnew2 = params.password_new2
        if (!password) {
            def failure = [status: 0, msg: message(code: 'operator.nopassword.message',default: 'No password')] as JSON
            render(failure.toString())
            return
        }
        if (!passwordnew) {
            def failure = [status: 0, msg: message(code: 'operator.nopasswordnew.message',default: 'No new password')] as JSON
            render(failure.toString())
            return
        }
        if (!passwordnew2) {
            def failure = [status: 0, msg: message(code: 'operator.nopasswordnew2.message',default: 'No confirm password')] as JSON
            render(failure.toString())
            return
        }
        if (passwordnew != passwordnew2) {
            def failure = [status: 0, msg: message(code: 'operator.passwordnotequal.message',default: 'Passwords are not equal')] as JSON
            render(failure.toString())
            return
        }

        password =  springSecurityService.encodePassword(password, userInstance.username)

        if (password != userInstance.password) {
            def failure = [status: 0, msg: message(code: 'operator.passwordincorrect.message',default: 'The current password is incorrect')] as JSON
            render(failure.toString())
            return
        }

        userInstance.password = passwordnew

        if (!userInstance.save(flush: true)) {
            def failure = [status: 0, msg: message(code: 'operator.passwordfailed.message',default: 'The password change failed')] as JSON
            render(failure.toString())
            return
        }

        if (springSecurityService.loggedIn &&
                springSecurityService.principal.username == userInstance.username) {
            springSecurityService.reauthenticate userInstance.username
        }

        def failure = [status: 1, msg: message(code: 'operator.passwordsuccess.message',default: 'The password change successfully')] as JSON
        render(failure.toString())
    }
}
